//
//  HomeSBCon.m
//  星期一
//
//  Created by 来定MAC on 15/8/3.
//  Copyright (c) 2015年 LD. All rights reserved.
//

#import "HomeSBCon.h"
#import <AFNetworking.h>
#import "Common.h"
#import "StartUpModel.h"
#import "UIView+SimpleFrame.h"
#import "HeadViewWithContentV.h"
#import "ContentTableView.h"
#import <MJExtension.h>
#import "VenuseModel.h"
#import "LSStringSize.h"

@interface HomeSBCon ()<UITableViewDelegate>

@property(nonatomic,strong)ContentTableView *contentView;


@end

@implementation HomeSBCon

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //数据请求
    [self loadContentWithNetwork];
    //下载推荐图通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadRemandViewImage:)name:@"downloadRemandImg" object:nil];
    [self.view addSubview:self.contentView];
    [self layoutSubviews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)layoutSubviews
{
    [self.contentView setFrame:self.view.bounds];
}

#pragma mark --networking Area
- (void)loadRemandViewImage:(NSNotification *)noti
{
    //获取本地地址目录
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMdd"];
    NSString *dateStr = [dateformatter stringFromDate:currentDate];
    NSString *remandImagePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"remandImage.png"];
    
    //判断今日是否已经进行了数据请求
    NSString *remandImageDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentDate"];
    //NSLog(@"datestr : %@,ramandImgDate : %@",dateStr,remandImageDate);
    if (![dateStr isEqualToString:remandImageDate]) {
        
        //网络请求
        NSString *url_str = [NSString stringWithFormat:@"http://p1.ishecdn.com/m/%@/300/0.png",noti.object];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                if([data writeToFile:remandImagePath atomically:YES])
                {
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:dateStr forKey:@"currentDate"];
                    [userDefaults synchronize];
                    LXLog(@"推荐图片写入本地成功");
                }
            }
            else
            {
                LXLog(@"获取推荐图失败 statuscode : %ld",(long)httpResponse.statusCode);
            }
        }];

    }
}

- (void)loadContentWithNetwork
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //http://apiv6.ixingji.com/ixingji/venus/gets.json?&uid=12583948&token=mLDxdDc6h8vusLyQ&pid=584&appid=584&client=iPhone&pname=X584I_122_A_011&size=10&start=0
    NSString *urlStr = @"http://apiv6.ixingji.com/ixingji/venus/gets.json";
    NSDictionary *parameter = [NSDictionary dictionaryWithObjectsAndKeys:
                               @12583948,@"uid",
                               @"mLDxdDc6h8vusLyQ",@"token",
                               @584,@"pid",
                               @584,@"appid",
                               @"iPhone",@"client",
                               @"X584I_122_A_011",@"pname",
                               @10,@"size",
                               @0,@"start",nil];
    [manager GET:urlStr parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        LXLog(@"首页内容数据载入成功");
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        NSArray *venuseArr = [[responseDic objectForKey:@"attachment"] objectForKey:@"venuses"];
        //LXLog(@"venuseArr : %@",venuseArr);setupObjectClassInArray
        [VenuseModel setupObjectClassInArray:^NSDictionary *{
            return @{@"venusDetails":@"VenusDetailModel"};
        }];
        NSArray *modelArr = [VenuseModel objectArrayWithKeyValuesArray:venuseArr];
        [self.contentView.venuseModelArr addObjectsFromArray:modelArr];
        [self.contentView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        LXLog(@"load content status : %ld",(long)operation.response.statusCode);
    }];
}

#pragma mark --delegate Area
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ContentTableView *tableView_C = (ContentTableView *)tableView;
    NSString *descrp = [[tableView_C.venuseModelArr objectAtIndex:indexPath.row] descrp];
    CGFloat descrpH = [LSStringSize getTheStringHeight:descrp setFont:17 withWidth:(self.view.width - 20)];
    return descrpH + 525;
}

#pragma mark --lazy load Area
- (UITableView *)contentView
{
    if (_contentView == nil) {
        _contentView = [[ContentTableView alloc] init];
        _contentView.delegate = self;
        _contentView.venuseModelArr = [NSMutableArray array];
    }
    return _contentView;
}


@end
